﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Castle.MonoRail.Framework.ViewComponents;
using System.Web;
using StateTheaterDataModel;
using System.Web.Security;
using System.Security.Principal;

namespace StateTheater.Component
{
	public class AutoLoginViewComponent : AuthenticatedContent
	{
		public StateTheaterDataContext db { get; set; }

		const string strUniqueID = "Snitz00User";

		public override void Render()
		{
			if ( ! IsAuthenticated())
			{
				var cookie = this.HttpContext.Request.Cookies[strUniqueID];
				if (cookie != null)
				{
					string username = cookie["Name"];
					string PWord = cookie["PWord"];
					var q = from u in db.FORUM_MEMBERs
							where u.M_NAME == username && u.M_PASSWORD == PWord
							select "Yes";

					if (q.Any())
					{
						FormsAuthentication.SetAuthCookie(username, true);
					}
				}
			}
			base.Render();
		}
		private bool IsAuthenticated()
		{
			IPrincipal user = EngineContext.CurrentUser;

			return user != null && user.Identity != null && user.Identity.IsAuthenticated;
		}
	}
}
